package ReenterantLock;

import sun.misc.Unsafe;

import java.util.concurrent.atomic.AtomicInteger;

public class MyReenterantLock {

    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long stateOffset;

    private static final int tryCasCount = 10;

    static {
        try {
            stateOffset = unsafe.objectFieldOffset
                    (AtomicInteger.class.getDeclaredField("state"));
        } catch (Exception ex) { throw new Error(ex); }
    }

    private volatile int state;


    // 是否公平
    private boolean fair;

    private BlockedThreadQueue blockedThreadQueue = new BlockedThreadQueue();

    /**
     * 加锁
     */
    public void lock(){
        if(fair){
            boolean isEnqueue = blockedThreadQueue.getSize()>0;
            if(isEnqueue){
                blockedThreadQueue.enQueue(Thread.currentThread());
            }else{
                int currentCasCount = tryCasCount;
                while(!unsafe.compareAndSwapInt(this, stateOffset, state, state + 1) && currentCasCount>0 ){
                    currentCasCount--;
                }
                blockedThreadQueue.enQueue(Thread.currentThread());
            }
        }else{
            int currentCasCount = tryCasCount;
            while(!unsafe.compareAndSwapInt(this, stateOffset, state, state + 1) && currentCasCount>0 ){
                currentCasCount--;
            }
            blockedThreadQueue.enQueue(Thread.currentThread());
        }
    }

    /**
     * 解锁
     */
    public void unlock(){
        state--;
        blockedThreadQueue.pollNode();
    }

}
